/*
 * Created by JFormDesigner on Tue Aug 02 13:54:22 EDT 2011
 */

package ca.etsmtl.log730.projet2.view;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.Queue;
import java.util.UUID;

import javax.swing.GroupLayout;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.CaretEvent;

import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingx.JXButton;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXLabel;
import org.jdesktop.swingx.JXTextArea;
import org.jdesktop.swingx.JXTextField;

import ca.etsmtl.log730.projet2.connectors.clientserver.LinkHandler;
import ca.etsmtl.log730.projet2.connectors.clientserver.RequestManager;
import ca.etsmtl.log730.projet2.connectors.clientserver.RequestManager.RequestListener;
import ca.etsmtl.log730.projet2.connectors.clientserver.nodes.DocumentMap.DocumentListener;
import ca.etsmtl.log730.projet2.connectors.msg.Request;
import ca.etsmtl.log730.projet2.documents.Document;
import ca.etsmtl.log730.projet2.users.User;

/**
 * @author Joe Labrosse
 */
public class JXDocumentEdit extends JXFrame implements RequestListener, DocumentListener {
	public JXDocumentEdit() {
		initComponents();
	}

	public Document getDocument() {
		return document;
	}

	public LinkHandler getLinkHandler() {
		return linkHandler;
	}

	private void thisWindowClosed(WindowEvent e) {
		linkHandler.getRequestManager().getDocumentMap().removeDocumentListener(this);
		linkHandler.getRequestManager().closeView(documentId);
	}

	private void btCloseActionPerformed(ActionEvent e) {
		// TODO add your code here
//		this.d
//		setVisible(false);
		dispose();
	}

	public String getData() {
		return data;
	}

	private void btEditCmdActionPerformed(ActionEvent e) {
		// TODO add your code here
		linkHandler.getRequestManager().openEdit(documentId);
	}

	private void btSaveActionPerformed(ActionEvent e) {
		// TODO add your code here
				Document d = new Document();
				d.setName(documentName.getText());
				d.clearData();
				d.getData().append(xTextArea1.getText());
				d.getAccess().getEditors().clear();
				d.getAccess().getViewers().clear();
				document.getAccess().getEditors().addAll(linkHandler.getRequestManager().getDocumentMap().getEditorQueue(documentId));
				document.getAccess().getViewers().addAll(linkHandler.getRequestManager().getDocumentMap().getViewers(documentId));
				linkHandler.getRequestManager().updateDocument(documentId, d);
			
	}

	private void btEditCmd2ActionPerformed(ActionEvent e) {
		linkHandler.getRequestManager().closeEdit(documentId);
		// TODO add your code here
	}

	private void xTextArea1CaretUpdate(CaretEvent e) {
		// TODO add your code here
	}

	private void xTextArea1InputMethodTextChanged(InputMethodEvent e) {
		// TODO add your code here
		System.out.println(e.getText().toString());
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Joe Labrosse
		scrollPane1 = new JScrollPane();
		xTextArea1 = new JXTextArea();
		btClose = new JXButton();
		xLabel1 = new JXLabel();
		documentName = new JXTextField();
		btEditCmd = new JXButton();
		btSave = new JXButton();
		docId = new JXLabel();
		btEditCmd2 = new JXButton();
		currentEditor = new JXTextField();
		editQueue = new JXTextField();
		document = new Document();
		linkHandler = new LinkHandler();
		data = new String();

		//======== this ========
		setTitle("Document - Edit/View");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				thisWindowClosed(e);
			}
		});
		Container contentPane = getContentPane();

		//======== scrollPane1 ========
		{

			//---- xTextArea1 ----
			xTextArea1.setPromptFontStyle(null);
			scrollPane1.setViewportView(xTextArea1);
		}

		//---- btClose ----
		btClose.setText("Close");
		btClose.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btCloseActionPerformed(e);
			}
		});

		//---- xLabel1 ----
		xLabel1.setText("Document Name:");

		//---- btEditCmd ----
		btEditCmd.setText("Edit!");
		btEditCmd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btEditCmdActionPerformed(e);
			}
		});

		//---- btSave ----
		btSave.setText("Save");
		btSave.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btSaveActionPerformed(e);
			}
		});

		//---- docId ----
		docId.setText("text");

		//---- btEditCmd2 ----
		btEditCmd2.setText("Release");
		btEditCmd2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btEditCmd2ActionPerformed(e);
			}
		});

		//---- currentEditor ----
		currentEditor.setEditable(false);

		//---- editQueue ----
		editQueue.setEditable(false);

		GroupLayout contentPaneLayout = new GroupLayout(contentPane);
		contentPane.setLayout(contentPaneLayout);
		contentPaneLayout.setHorizontalGroup(
			contentPaneLayout.createParallelGroup()
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(contentPaneLayout.createParallelGroup()
						.addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
						.addGroup(contentPaneLayout.createSequentialGroup()
							.addComponent(btEditCmd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(btEditCmd2, GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(currentEditor, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(editQueue, GroupLayout.PREFERRED_SIZE, 288, GroupLayout.PREFERRED_SIZE)
							.addGap(18, 18, 18)
							.addComponent(btSave, GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(btClose, GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
						.addGroup(contentPaneLayout.createSequentialGroup()
							.addComponent(xLabel1, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(documentName, GroupLayout.PREFERRED_SIZE, 190, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
							.addComponent(docId, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		contentPaneLayout.setVerticalGroup(
			contentPaneLayout.createParallelGroup()
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
						.addComponent(xLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(documentName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(docId, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
					.addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 427, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
						.addComponent(btEditCmd, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btClose, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(btSave, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btEditCmd2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(currentEditor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(editQueue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		pack();
		setLocationRelativeTo(getOwner());

		//---- bindings ----
		bindingGroup = new BindingGroup();
		{
			Binding binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
				this, ELProperty.create("${documentId.toString}"),
				docId, BeanProperty.create("text"));
			binding.setSourceNullValue(null);
			binding.setSourceUnreadableValue(null);
			bindingGroup.addBinding(binding);
		}
		{
			Binding binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
				document, ELProperty.create("${name}"),
				documentName, BeanProperty.create("text"));
			binding.setSourceNullValue(null);
			binding.setSourceUnreadableValue(null);
			binding.setTargetNullValue(null);
			bindingGroup.addBinding(binding);
		}
		bindingGroup.bind();
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Joe Labrosse
	private JScrollPane scrollPane1;
	private JXTextArea xTextArea1;
	private JXButton btClose;
	private JXLabel xLabel1;
	private JXTextField documentName;
	private JXButton btEditCmd;
	private JXButton btSave;
	private JXLabel docId;
	private JXButton btEditCmd2;
	private JXTextField currentEditor;
	private JXTextField editQueue;
	private Document document;
	private LinkHandler linkHandler;
	private String data;
	private BindingGroup bindingGroup;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
	
	
	public UUID documentId = null;
	
	public void setDocumentId(UUID id) {
		documentId = id;
		Document c = linkHandler.getRequestManager().getDocumentMap().get(id);
		
		document.setName(c.getName());
//		document.getData().delete(0, document.getData().length());
//		document.getData().append(c.getData());
		document.getAccess().getEditors().clear();
		document.getAccess().getViewers().clear();
		document.getAccess().getEditors().addAll(c.getAccess().getEditors());
		document.getAccess().getViewers().addAll(c.getAccess().getViewers());
		bindingGroup.unbind();
//		document = c;
		xTextArea1.setText(c.getData().toString());
		boolean view = true;
		User currentUseru = null;
		currentEditor.setText("");
		editQueue.setText("");
		Queue<User> queue = linkHandler.getRequestManager().getDocumentMap().getEditorQueue(id);
		if(!linkHandler.getRequestManager().getDocumentMap().getEditorQueue(id).isEmpty()) {
			currentUseru = linkHandler.getRequestManager().getDocumentMap().getEditorQueue(id).peek();
			currentEditor.setText(currentUseru.getName());
			
			Iterator<User> it = linkHandler.getRequestManager().getDocumentMap().getEditorQueue(id).iterator();
			it.next();
			
			StringBuffer queuetext = new StringBuffer();
			while(it.hasNext()) {
				queuetext.append("[" + it.next().getName().toString() + "] ");
			}
			editQueue.setText(queuetext.toString());
			
		}
		
		System.out.println(currentUseru + " == " + linkHandler.getNodesMap().getCurrentNode().getUser().toString());
		if(currentUseru != null &&
				currentUseru.equals(linkHandler.getNodesMap().getCurrentNode().getUser())) {
			view = false;
		}
		if(queue.contains(linkHandler.getNodesMap().getCurrentNode().getUser())) {
			btEditCmd.setEnabled(false);
			btEditCmd2.setEnabled(true);

		} else {
			btEditCmd.setEnabled(view);
			btEditCmd2.setEnabled(!view);
		}
		btSave.setEnabled(!view);
		xTextArea1.setEnabled(!view);
		documentName.setEnabled(!view);
		bindingGroup.bind();
		System.out.println("DOCUMENT SET: " + document.getName());
	}
	public UUID getDocumentId() {
		return documentId;
	}
	public void setLinkHandler(LinkHandler lh) {
		linkHandler = lh;
		linkHandler.getRequestManager().getDocumentMap().addDocumentListener(this);

	}

	@Override
	public void requestSent(RequestManager rm, Request r) {
	}

	@Override
	public void requestReplyReceived(RequestManager rm, Request r, float t) {
	}

	@Override
	public void requestConfirmed(RequestManager rm, Request r, boolean accepted) {
	}

	@Override
	public void requestDisposed(RequestManager rm, Request r) {
		rm.unregister(this, r);
	}
	
	
	public void setData(String d) {
		data = d;
	}

	@Override
	public void updated(final UUID id, Document d) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				setDocumentId(id);
				
			}
		});
	}
}
